using System;
using System.IO;

namespace Conusic
{
    public class BitrateFinder
    {
        public BitrateFinder()
        {
        }

        private readonly int[] bitrateToNumberic = new int[]
                                                       {
                                                           0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320
                                                           , 0
                                                       };

        public int findBitrate(Stream stream)
        {
            const int MPEG_AUDIO_FRAME_BUFFER_SIZE = 4;
            var buffer = new byte[MPEG_AUDIO_FRAME_BUFFER_SIZE];
            if (stream.Read(buffer, 0, buffer.Length) == MPEG_AUDIO_FRAME_BUFFER_SIZE)
            {
                //http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(buffer);

                int frameBuffer = BitConverter.ToInt32(buffer, 0);
                int bitrate = (frameBuffer >> 12) & 15;


                return bitrateToNumberic[bitrate];
            }
            else
            {
                throw new IOException();
            }
        }
    }
}